<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/21 0021
 * Time: 17:35
 */

namespace app\index\controller;

use app\index\model\UserRess;
use think\Controller;
use think\Loader;
use think\Db;

class ReapRess extends Controller
{
	/**
	 * 收货地址主页
	 */
	public function index()
	{
		$ress = Db::name('user')
			->alias('t1')
			->field('t2.*')
			->join('user_ress t2', 't1.uid = t2.uid')
			->where('t2.del_time',null)
			->where('t1.uid',session('uid'))
			->select();
		$this->assign('ress', $ress);
		return $this->fetch();
	}


	/**
	 * 所有地址中选择默认地址   设置成默认地址
	 */
	public function defaultRess()
	{
		$post = input('post.');
		$res = Db::name('user')
			->alias('t1')
			->join('user_ress t2', 't1.uid = t2.uid')
			->where('t2.checked', 1)
			->find();
		if ($res) {
			UserRess::where('rid', $res['rid'])
				->update(['checked' => 0]);
			UserRess::where('rid', $post['rid'])
				->update(['checked' => 1]);
		}else{
			UserRess::where('rid', $post['rid'])
				->update(['checked' => 1]);
		}
	}


	/**
	 * 编辑地址
	 */
	public function editRess(){
		return $this->fetch();
	}


	/**
	 * 添加地址主页
	 */
	public function Ress()
	{
		return $this->fetch();
	}


	/**
	 * 添加地址，是否设置为默认地址
	 */
	public function addRess()
	{
		$post = input('post.');
		$validate = Loader::validate('AddRess');
		if (!$validate->check($post)) {
			$this->error($validate->getError());
		}
		if (session('uid')) {
			if (isset($post['checked'])) {
				$res = Db::name('user')
					->alias('t1')
					->join('user_ress t2', 't1.uid = t2.uid')
					->where('t2.del_time', null)
					->where('t2.checked', 1)
					->find();
				if ($res) {
					//采用select查询可以使用循环更新
//					foreach ($res as $v){
//						UserRess::where('rid', $v['rid'])
//							->update(['checked' => '0']);
//					}
					UserRess::where('rid', $res['rid'])
						->update(['checked' => 0]);
					$post['uid'] = session('uid');
					$post['rtime'] = time();
					$ress = UserRess::create($post);
					if ($ress) {
						$this->success('已添加');
					} else {
						$this->error('添加失败，请稍后在试');
					}
				} else {
					$post['uid'] = session('uid');
					$post['rtime'] = time();
					$res = UserRess::create($post);
					if ($res) {
						$this->success('已添加');
					} else {
						$this->error('添加失败，请稍后在试');
					}
				}
			} else {
				$post['uid'] = session('uid');
				$post['rtime'] = time();
				$res = UserRess::create($post);
				if ($res) {
					$this->success('已添加');
				} else {
					$this->error('添加失败，请稍后在试');
				}
			}
		} else {
			$this->error('请先登陆');
		}
	}


	/**
	 * 软删除地址  删除同时把地址状态设置为不是默认地址
	 */
	public function delRess(){
		$rid = input('rid');
		$res = UserRess::destroy($rid);
		if ($res){
			Db::name('user_ress')->where('rid', $rid)->update(['checked' => 0]);
			$this->success('已删除');
		}else{
			$this->error('删除失败，请稍后再试');
		}
	}
}